//
//  KLMyLockTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/5/16.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLMyLockTableViewController.h"
#import "KLScanCodeViewController.h"
#import "KLHttpAPI.h"
#import "KLHelp.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "Masonry.h"
#import "BuleFuction.h"
#import "KLSingleLockInfoTableViewController.h"
#import "FRDLivelyButton.h"
#import "MLKMenuPopover.h"
#import "ZYPinYinSearch.h"
#import "SSKeychain.h"
#import "UIAlertView+Blocks.h"
#import "UIActionSheet+Blocks.h"
#import "RIButtonItem.h"
#import "MBProgressHUDManager.h"
#import "KLAddLockGroupVC.h"
#import "KLBrunchDetailViewController.h"
#import "KLSendBrunchViewController.h"
#import "KLAuthorizationTVC.h"

// 扫描优化
#import "LBXScanViewStyle.h"
#import "KLRBScanViewController.h"
@interface KLMyLockTableViewController ()<UISearchResultsUpdating,MLKMenuPopoverDelegate>
{
    UISegmentedControl *segContontrol;
    NSInteger isFirstMaster;
}

@property (nonatomic,strong) NSMutableArray *lock_list_arr;//搜索前的数据源
@property (nonatomic,strong) NSMutableArray *searchingArr;//搜索时的数据源

@property (nonatomic,strong) UISearchController *searchController;

@property(nonatomic,strong) MLKMenuPopover *menuPopover; //弹出视图
@property(nonatomic,strong) NSArray *menuItems; //弹出的菜单数组

@property(nonatomic,strong) NSMutableArray *firstMaster; //一级锁主
@property(nonatomic,strong) NSMutableArray *secondMaster; //二级锁主
@property(nonatomic,strong) NSMutableArray *bunchMaster; //钥匙串

@end


@implementation KLMyLockTableViewController
- (UISearchController *)searchController {
    if (!_searchController) {
        _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.hidesNavigationBarDuringPresentation = NO;
        _searchController.searchBar.placeholder = @"搜索";
        [_searchController.searchBar sizeToFit];
    }
    return _searchController;
}

-(NSMutableArray *)lock_list_arr{
    if(!_lock_list_arr){
        _lock_list_arr = [NSMutableArray array];
    }
    return _lock_list_arr;
}

-(NSMutableArray *)searchingArr{
    if(!_searchingArr){
        _searchingArr = [NSMutableArray array];
    }
    return _searchingArr;
}

-(NSMutableArray *)firstMaster{
    if(!_firstMaster){
        _firstMaster = [NSMutableArray array];
    }
    return _firstMaster;
}

-(NSMutableArray *)secondMaster{
    if(!_secondMaster){
        _secondMaster = [NSMutableArray array];
    }
    return _secondMaster;
}

-(NSMutableArray *)bunchMaster{
    if(!_bunchMaster){
        _bunchMaster = [NSMutableArray array];
    }
    return _bunchMaster;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    isFirstMaster = 0;
    //初始化头视图
    [self headView];
    //初始化导航栏
    [self naveSet];
    
    //刷新锁列表
    [self refreshLockList];
    
    //注册当扫描二维码成功时刷新锁列表信息的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(codeScanSuccess:) name:@"scanSuccess" object:nil];
    //注册当新建钥匙串成功时的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(creatBrunchSuccess:) name:@"brunchSuccess" object:nil];
    //当修改钥匙串名称成功时的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(creatBrunchSuccess:) name:@"editBrunchNameSuccess" object:nil];
}-(void)codeScanSuccess:(id)sender{
    segContontrol.selectedSegmentIndex = 0;
    [self changeLockListInSegment:segContontrol];
    [self refreshLockList];
}-(void)creatBrunchSuccess:(id)sender{
    segContontrol.selectedSegmentIndex = 2;
    [self changeLockListInSegment:segContontrol];
}

#pragma mark - Tableview代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchController.active){
        return self.searchingArr.count;
    }else{
        if(self.lock_list_arr.count != 0){
            [KLHelp removeImgViewAndNoticeLabel];
        }
        return self.lock_list_arr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"locklist"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"locklist"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    UIImageView *iv = [[UIImageView alloc]init];
    if(isFirstMaster == 0 || isFirstMaster == 1){
        iv.image = [UIImage imageNamed:@"lockround"];
    }else if(isFirstMaster == 2){
        iv.image = [UIImage imageNamed:@"钥匙-线"];
    }
    [cell.contentView addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cell);
        make.size.mas_equalTo(CGSizeMake(29, 38));
        make.left.equalTo(cell).with.offset(25);
    }];

    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    if(isFirstMaster == 0 || isFirstMaster == 1){
        if (self.searchController.active){
            NSDictionary *lockDic = self.searchingArr[indexPath.row];
            nameLabel.text = [lockDic objectForKey:@"name"];
        }else{
//            NSLog(@"lock_list_arr:%@",self.lock_list_arr);
            NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
            nameLabel.text = [NSString stringWithFormat:@"别名：%@",[lockDic objectForKey:@"name"]];
        }
    }else if (isFirstMaster == 2){
        if (self.searchController.active){
            NSDictionary *keyBrunchDic = self.searchingArr[indexPath.row];
            nameLabel.text = [NSString stringWithFormat:@"钥匙串名:%@",[keyBrunchDic objectForKey:@"group_name"]];
        }else{
            NSDictionary *keyBrunchDic = self.lock_list_arr[indexPath.row];
            nameLabel.text = [NSString stringWithFormat:@"钥匙串名:%@",[keyBrunchDic objectForKey:@"group_name"]];
        }
    }
    nameLabel.font = [UIFont systemFontOfSize:16];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell.contentView).with.offset(3);
        make.right.equalTo(cell.contentView).with.offset(-60);
        make.height.mas_equalTo(30);
        make.left.equalTo(iv).with.offset(40);
    }];
    
    UILabel *addressLabel = [[UILabel alloc]init];
//    addressLabel.lineBreakMode = UILineBreakModeMiddleTruncation; //iOS 6 之后弃用
    addressLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    if(isFirstMaster == 0 || isFirstMaster == 1){
        if (self.searchController.active){
            NSDictionary *lockDic = self.searchingArr[indexPath.row];
            addressLabel.text = [lockDic objectForKey:@"address"];
        }else{
            NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
            addressLabel.text = [NSString stringWithFormat:@"地址：%@",[lockDic objectForKey:@"address"]];
        }
    }else if (isFirstMaster == 2){
        if (self.searchController.active){
            NSDictionary *lockDic = self.searchingArr[indexPath.row];
            addressLabel.text = [NSString stringWithFormat:@"包含锁数量:%@把",[lockDic objectForKey:@"count"]];
        }else{
            NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
            addressLabel.text = [NSString stringWithFormat:@"包含锁数量:%@把",[lockDic objectForKey:@"count"]];
        }
    }
    addressLabel.font = [UIFont systemFontOfSize:14];
    addressLabel.textColor = RGB_UI_COLOR(120, 120, 120);
    addressLabel.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:addressLabel];
    [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(cell.contentView).with.offset(-3);
        make.right.equalTo(cell.contentView).with.offset(-60);
        make.height.mas_equalTo(30);
        make.left.equalTo(iv).with.offset(40);
    }];
    
    //是否允许暴露给其它用户申请
    NSDictionary *lockDic;
    if(self.searchController.active){
        lockDic = self.searchingArr[indexPath.row];
    }else{
        lockDic = self.lock_list_arr[indexPath.row];
    }
    NSString *status;
    NSString *lockId;
    if(isFirstMaster == 0 || isFirstMaster == 1){
        status = [lockDic objectForKey:@"status"];
        lockId = [lockDic objectForKey:@"id"];
    }else if (isFirstMaster == 2){
        status = [lockDic objectForKey:@"status"];
        lockId = [lockDic objectForKey:@"id"];
    }
    UISwitch *switchBtn = [[UISwitch alloc]init];
    switchBtn.on = status.boolValue;
    switchBtn.tag = lockId.integerValue;
    [cell.contentView addSubview:switchBtn];
    [switchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.centerY.equalTo(cell.contentView);
    }];
    [switchBtn addTarget:self action:@selector(allowdRequest:) forControlEvents:UIControlEventValueChanged];
    
    return cell;
}-(void)allowdRequest:(UISwitch *)sender{
    if(isFirstMaster == 0 || isFirstMaster == 1){
        if(sender.on == YES){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"允许其它用户申请" message:@"点击“确定”，允许该锁显示给其它用户申请钥匙！" cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
                sender.on = NO;
            }] otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
                [KLHelp showHUDAddedTo:self.view animated:YES];
                [KLHttpAPI isTheLockAllowdToBeApplyWithStatus:@"1" lockID:[NSString stringWithFormat:@"%zd",sender.tag] completionHandler:^(MKNetworkOperation *operation) {
                    NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        [self refreshLockList];
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"允许申请权限已打开" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        [alert show];
                    }else{
                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                    }
                } errorHandler:^(NSString *error) {
                }];
            }], nil];
            [alert show];
        }else if (sender.on == NO){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"禁止其它用户申请" message:@"点击“确定”，禁止该锁显示给其它用户申请钥匙！" cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
                sender.on = YES;
            }] otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
                [KLHelp showHUDAddedTo:self.view animated:YES];
                [KLHttpAPI isTheLockAllowdToBeApplyWithStatus:@"0" lockID:[NSString stringWithFormat:@"%zd",sender.tag] completionHandler:^(MKNetworkOperation *operation) {
                    NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        [self refreshLockList];
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"允许申请权限已关闭" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        [alert show];
                    }else{
                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                    }
                } errorHandler:^(NSString *error) {
                }];
            }], nil];
            [alert show];
        }
    }else if (isFirstMaster == 2){
        if(sender.on == YES){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"允许其它用户申请" message:@"点击“确定”，允许该钥匙串显示给其它用户申请钥匙！" cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
                sender.on = NO;
            }] otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
                [KLHelp showHUDAddedTo:self.view animated:YES];
                [KLHttpAPI requestAllowedKeysBrunchApplyedWithFrom_id:[NSString stringWithFormat:@"%zd",sender.tag] type:@"1" status:@"1" completionHandler:^(MKNetworkOperation *operation) {
                    NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        [self getALlBrunchKeys];
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"允许申请权限已打开" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        [alert show];
                    }else{
                        [KLHelp hideAllHUDsForView:self.view animated:YES];
                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                    }
                } errorHandler:^(NSString *error) {
                    [KLHelp hideAllHUDsForView:self.view animated:YES];
                }];
            }], nil];
            [alert show];
        }else if (sender.on == NO){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"禁止其它用户申请" message:@"点击“确定”，禁止该钥匙串显示给其它用户申请钥匙！" cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:^{
                sender.on = YES;
            }] otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
                [KLHelp showHUDAddedTo:self.view animated:YES];
                [KLHttpAPI requestAllowedKeysBrunchApplyedWithFrom_id:[NSString stringWithFormat:@"%zd",sender.tag] type:@"1" status:@"0" completionHandler:^(MKNetworkOperation *operation) {
                    NSString *isSuccess = [operation.responseJSON objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        [self getALlBrunchKeys];
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"允许申请权限已关闭" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                        [alert show];
                    }else{
                        [KLHelp hideAllHUDsForView:self.view animated:YES];
                        [KLHelp showTextHUDforView:self.view text:[operation.responseJSON objectForKey:@"msg"]];
                    }
                } errorHandler:^(NSString *error) {
                    [KLHelp hideAllHUDsForView:self.view animated:YES];
                }];
            }], nil];
            [alert show];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(isFirstMaster == 0 || isFirstMaster == 1){
        KLSingleLockInfoTableViewController *singleLockInfoVC = [[KLSingleLockInfoTableViewController alloc]init];
        if(self.searchController.active){
            singleLockInfoVC.currentLockInfoDic = self.searchingArr[indexPath.row];
        }else{
            singleLockInfoVC.currentLockInfoDic = self.lock_list_arr[indexPath.row];
        }
        singleLockInfoVC.isFirstMaster = !isFirstMaster;
        [self.navigationController pushViewController:singleLockInfoVC animated:YES];
    }else if(isFirstMaster == 2){
        if(self.searchController.active){
            KLBrunchDetailViewController *brunchDetail = [[KLBrunchDetailViewController alloc]initWithNibName:@"KLBrunchDetailViewController" bundle:nil];
            brunchDetail.groupDic = [self.searchingArr[indexPath.row] copy];
            brunchDetail.firstMaster = [self.firstMaster copy];
            brunchDetail.secondMaster = [self.secondMaster copy];
            [self.navigationController pushViewController:brunchDetail animated:YES];
        }else{
            KLBrunchDetailViewController *brunchDetail = [[KLBrunchDetailViewController alloc]initWithNibName:@"KLBrunchDetailViewController" bundle:nil];
            brunchDetail.groupDic = [self.lock_list_arr[indexPath.row] copy];
            brunchDetail.firstMaster = [self.firstMaster copy];
            brunchDetail.secondMaster = [self.secondMaster copy];
            [self.navigationController pushViewController:brunchDetail animated:YES];
        }
    }
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if(isFirstMaster == 2){
//        NSDictionary *groupDic = self.lock_list_arr[indexPath.row];
//        NSString *type = [groupDic objectForKey:@"type"];
//        if(type.integerValue == 1)
        return YES;
//        else
//            return NO;
    }else
        return NO;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *groupDic = self.lock_list_arr[indexPath.row];
    NSString *type = [groupDic objectForKey:@"type"];
    //分发钥匙串
    UITableViewRowAction *action0 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"分发" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"分发%zd",indexPath.row);
//        if(groupright.integerValue == 3){
        KLSendBrunchViewController *sendBrunch = [[KLSendBrunchViewController alloc]init];
        sendBrunch.groupDic = [self.lock_list_arr[indexPath.row] copy];
        [self.navigationController pushViewController:sendBrunch animated:YES];
        // 收回左滑出现的按钮(退出编辑模式)
        tableView.editing = NO;
//        }else{
//            [KLHelp showTextHUDforView:self.view text:@"该钥匙串不可分发"];
//        }
    }];
    action0.backgroundColor = [UIColor greenColor];
    //删除模板钥匙串
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"删除%zd",indexPath.row);
        tableView.editing = NO;
        NSString *brunch_id = [groupDic objectForKey:@"id"];
        if(type.integerValue == 1){//删除模板钥匙串
            [KLHelp showHUDAddedTo:self.view animated:YES];
            [KLHttpAPI deleteUserDefineBrunchWithBrunch_id:brunch_id completionHandler:^(MKNetworkOperation *operation) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                NSDictionary *dic = operation.responseJSON;
                [KLHelp showTextHUDforView:self.view text:[dic objectForKey:@"msg"]];
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [self getALlBrunchKeys];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                [KLHelp showTextHUDforView:self.view text:error];
            }];
        }else if(type.integerValue == 2){
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:nil] destructiveButtonItem:nil otherButtonItems:[RIButtonItem itemWithLabel:@"同时删除该钥匙串下发的子钥匙" action:^{
                [KLHelp showHUDAddedTo:self.view animated:YES];
                [KLHttpAPI deleteAllLockBrunchWithGroup_transfer_id:brunch_id type:@"1" completionHandler:^(MKNetworkOperation *operation) {
                    [KLHelp hideAllHUDsForView:self.view animated:YES];
                    NSLog(@"同时删除该钥匙串下发的子钥匙返回数据:%@",operation.responseString);
                    NSDictionary *dic = operation.responseJSON;
                    NSString *isSuccess = [dic objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        [self getALlBrunchKeys];
                    }
                    [KLHelp showTextHUDforView:self.view text:[dic objectForKey:@"msg"]];
                } errorHandler:^(NSString *error) {
                    [KLHelp hideAllHUDsForView:self.view animated:YES];
                    [KLHelp showTextHUDforView:self.view text:error];
                }];
            }], [RIButtonItem itemWithLabel:@"保留该钥匙串下发的子钥匙" action:^{
                [KLHelp showHUDAddedTo:self.view animated:YES];
                [KLHttpAPI deleteAllLockBrunchWithGroup_transfer_id:brunch_id type:@"1" completionHandler:^(MKNetworkOperation *operation) {
                    [KLHelp hideAllHUDsForView:self.view animated:YES];
                    NSLog(@"同时删除该二级锁主下发的子钥匙返回数据:%@",operation.responseString);
                    NSDictionary *dic = operation.responseJSON;
                    NSString *isSuccess = [dic objectForKey:@"success"];
                    if(isSuccess.integerValue == 1){
                        [self getALlBrunchKeys];
                    }
                    [KLHelp showTextHUDforView:self.view text:[dic objectForKey:@"msg"]];
                }errorHandler:^(NSString *error) {
                    [KLHelp hideAllHUDsForView:self.view animated:YES];
                    [KLHelp showTextHUDforView:self.view text:error];
                }];
            }],nil];
            [sheet showInView:self.view];
        }
    }];
    action1.backgroundColor = [UIColor redColor];
    //授权二级钥匙串
    UITableViewRowAction *action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"授权" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        if(type.integerValue == 1){
            tableView.editing = NO;
            NSLog(@"授权%zd",indexPath.row);
            KLAuthorizationTVC *authorizationTvc = [[KLAuthorizationTVC alloc]init];
            authorizationTvc.groupDic = [self.lock_list_arr[indexPath.row] copy];
            [self.navigationController pushViewController:authorizationTvc animated:YES];
        }else{
            [KLHelp showTextHUDforView:self.view text:@"二级钥匙串不可授权"];
        }
    }];
    if(type.integerValue == 1){
        action2.backgroundColor = [UIColor yellowColor];
    }else{
        action2.backgroundColor = [UIColor grayColor];
    }
    return @[action2,action0,action1];
}

#pragma mark - 界面设置
//初始化导航栏
-(void)naveSet{
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.navigationController.navigationBarHidden = NO;
    // 设置导航条的titleView内容
    segContontrol = [[UISegmentedControl alloc] initWithItems:@[@"一级锁主",@"二级锁主",@"钥匙串"]];
    [segContontrol setTintColor:RGB_UI_COLOR(0, 204, 102)];
    // 设置选中的文字颜色
    [segContontrol setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateSelected];
    segContontrol.selectedSegmentIndex = 0;
    //设置分段控件点击相应事件
    [segContontrol addTarget:self action:@selector(changeLockListInSegment:)forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segContontrol;
    
    //设置导航栏返回按钮
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
    
    FRDLivelyButton *button = [[FRDLivelyButton alloc] initWithFrame:CGRectMake(0,0,20,20)];
    [button setOptions:@{ kFRDLivelyButtonLineWidth: @(1.0f),
                          kFRDLivelyButtonColor: [UIColor whiteColor]
                          }];
    [button setStyle:kFRDLivelyButtonStylePlus animated:NO];
    [button addTarget:self action:@selector(doActions:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = buttonItem;
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
    
}-(void)doActions:(FRDLivelyButton *)sender{
    self.menuPopover.menuPopoverDelegate = self;
    if(sender.buttonStyle == kFRDLivelyButtonStylePlus){
        [sender setStyle:kFRDLivelyButtonStyleClose animated:YES];
        self.menuPopover = [[MLKMenuPopover alloc] initWithFrame:CGRectMake(UI_View_Width-155, 55, 150, 88) menuItems:self.menuItems];
        self.menuPopover.menuPopoverDelegate = self;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [self.menuPopover showInView:window And:sender];
    }else if(sender.buttonStyle == kFRDLivelyButtonStyleClose){
        [sender setStyle:kFRDLivelyButtonStylePlus animated:YES];
        // Hide already showing popover
        [self.menuPopover dismissMenuPopover];
    }
}

-(void)changeLockListInSegment:(UISegmentedControl *)segmentControl{
    NSInteger index = segmentControl.selectedSegmentIndex;
    switch (index) {
        case 0:
            self.lock_list_arr = [self.firstMaster copy];
            self.searchController.active = NO;
            isFirstMaster = 0;
            break;
        case 1:
            self.lock_list_arr = [self.secondMaster copy];
            self.searchController.active = NO;
            isFirstMaster = 1;
            break;
        case 2:
            self.searchController.active = NO;
            [self getALlBrunchKeys];
            isFirstMaster = 2;
            break;
        default:
            break;
    }
    if(isFirstMaster == 0 || isFirstMaster == 1){
        if(self.lock_list_arr.count == 0){
            //创建无数据和无网时的图片
            [KLHelp setNoDateImageWithView:self.view type:0];
        }else{
            [KLHelp removeImgViewAndNoticeLabel];
        }
    }
    
    [self.tableView reloadData];
}

//初始化头视图
-(void)headView{
    self.menuItems = [NSArray arrayWithObjects:@"扫一扫", @"添加钥匙串",nil];
    self.tableView.tableHeaderView = self.searchController.searchBar;
}

#pragma mark -搜索框代理
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    if(searchController.active == NO)
        return ;
    [self.searchingArr removeAllObjects];
    
    NSArray *ary = [NSArray new];
    if(isFirstMaster == 0 || isFirstMaster == 1){
        ary = [ZYPinYinSearch searchWithOriginalArray:self.lock_list_arr andSearchText:searchController.searchBar.text andSearchByPropertyName:@"name"];
    }else if (isFirstMaster == 2){
        ary = [ZYPinYinSearch searchWithOriginalArray:self.lock_list_arr andSearchText:searchController.searchBar.text andSearchByPropertyName:@"group_name"];
    }
    if (searchController.searchBar.text.length == 0) {
        [self.searchingArr addObjectsFromArray:self.lock_list_arr];
    }else {
        [self.searchingArr addObjectsFromArray:ary];
    }
    [self.tableView reloadData];
}

#pragma mark - 弹出视图的代理
- (void)menuPopover:(MLKMenuPopover *)menuPopover didSelectMenuItemAtIndex:(NSInteger)selectedIndex{
    [self.menuPopover dismissMenuPopover];
    if(selectedIndex == 0){
//        KLScanCodeViewController *codeScanVC = [[KLScanCodeViewController alloc]init];
//        [self.navigationController pushViewController:codeScanVC animated:YES];
        
        // 扫码优化
        if (![self cameraPemission]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请设置相机权限打开" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"前往设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //        NSURL *url = [NSURL URLWithString:@"App-Prefs:root=Bluetooth"];//UIApplicationOpenSettingsURLString为跳往app设置
                NSURL *url = [NSURL URLWithString:@"App-Prefs:root=com.whguoyang.kisslock"];
                if ([[UIApplication sharedApplication]canOpenURL:url]) {
                    [[UIApplication sharedApplication]openURL:url];
                }
                
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:true completion:nil];
            return;
        }
        [self qqStyle];
        
    }else if(selectedIndex == 1){
        if(self.firstMaster.count == 0 && self.secondMaster.count == 0){
            [JRToast showWithText:@"您尚未拥有任何锁"];
            return;
        }
        
        //这里写推出添加锁组控制器的逻辑
        KLAddLockGroupVC *addLockVC = [[KLAddLockGroupVC alloc]init];
        addLockVC.firstMaster = [self.firstMaster copy];
        addLockVC.secondMaster = [self.secondMaster copy];
        [self.navigationController pushViewController:addLockVC animated:YES];
    }
}

#pragma mark - 刷新锁列表
-(void)refreshLockList{
    NSLog(@"self.firstMaster:%@",self.firstMaster);
//    [self.firstMaster removeAllObjects];
//    [self.secondMaster removeAllObjects];
    self.firstMaster = [NSMutableArray array];
    self.secondMaster = [NSMutableArray array];
    //刷新锁列表
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI requestLockListWith:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] completionHandler:^(NSDictionary *responseDic) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSLog(@"锁列表返回信息:%@",responseDic);
        NSLog(@"**************************************************");
        NSString *isSuccess = [responseDic objectForKey:@"success"];
        NSMutableArray *listItems = [NSMutableArray array];
        NSMutableArray *lock_grant = [NSMutableArray array];
        if(isSuccess.integerValue == 1){
            NSArray *infor = [responseDic objectForKey:@"infor"];
            for (NSDictionary *dic in infor) {
                NSString *type = [dic objectForKey:@"type"];
                if(type.integerValue == 1){
                    [listItems addObject:dic];
                }else if(type.integerValue == 2){
                    [lock_grant addObject:dic];
                }
            }
            if(listItems.count != 0){
                [KLHelp setNoDateImageWithView:self.view type:0];
                self.firstMaster = [listItems copy];
            }
        
            if(lock_grant.count != 0){
                [KLHelp setNoDateImageWithView:self.view type:0];
                self.secondMaster = [lock_grant copy];
            }
            
            if(isFirstMaster == 0){
                self.lock_list_arr = [self.firstMaster copy];
                NSLog(@"self.firstMaster:%@",self.firstMaster);
            }else if(isFirstMaster == 1){
                self.lock_list_arr = [self.secondMaster copy];
            }
            [self.tableView reloadData];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"backToLockList" object:nil];
            
            if(self.lock_list_arr.count == 0){
                //创建无数据和无网时的图片
                [KLHelp setNoDateImageWithView:self.view type:0];
            }else{
                [KLHelp removeImgViewAndNoticeLabel];
            }
            [KLHelp hideAllHUDsForView:self.view animated:YES];
        }else{
            [JRToast showWithText:[responseDic objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [KLHelp setNoDateImageWithView:self.view type:1];
    }];
}

-(void)dealloc{
    [self.searchController dismissViewControllerAnimated:YES completion:nil];
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI requestKeyListWith:token completionHandler:^(NSDictionary *responseDic) {
        NSString *isSuccess = [responseDic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            NSDictionary *infor = [responseDic objectForKey:@"infor"];
            NSArray *listItems = [infor objectForKey:@"listItems"];
            if(![[infor objectForKey:@"totalCount"] isEqualToString:@"0"] && ![[infor objectForKey:@"listItems"] isKindOfClass:[NSNull class]]){
                NSMutableArray *key_list_arr = [NSMutableArray arrayWithArray:listItems];
                //拿到钥匙列表后存入底层
                NSMutableArray *masterKeysArr = [NSMutableArray array];
                NSMutableArray *childKeysArr = [NSMutableArray array];
                //目前存的只有锁主钥匙,之后要做判断，并分开存储锁主钥匙和子钥匙
                for (NSDictionary *keyDic in key_list_arr) {
//                    NSString *valid_type = [keyDic objectForKey:@"valid_type"];
//                    if(valid_type.integerValue == 1 || valid_type.integerValue == 2){
//                        continue;
//                    }
                    
                    NSString *type = [keyDic objectForKey:@"keyright"];
                    if(type.integerValue == 3){//0是不可转发钥匙，1是可转发钥匙，2是二级锁主钥匙，3是锁主钥匙
                        [masterKeysArr addObject:keyDic];
                    }else{
//                        NSString *parentFlag = [keyDic objectForKey:@"parentflag"];//2是发出的钥匙，3是收到的钥匙
//                        if(parentFlag.integerValue == 3){
                            [childKeysArr addObject:keyDic];
//                        }
                    }
                }
                NSLog(@"锁主钥匙;%@",masterKeysArr);
                [[NSUserDefaults standardUserDefaults] setObject:masterKeysArr forKey:MASTER_KEY_ARRAY];
                [[NSUserDefaults standardUserDefaults] setObject:childKeysArr forKey:SUBMIT_KEY_ARRAY];
            }else{
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:MASTER_KEY_ARRAY];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:SUBMIT_KEY_ARRAY];
            }
        }
    } errorHandler:^(NSString *error) {
    }];
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.searchController.searchBar setHidden:YES];
    [self.searchController.searchBar resignFirstResponder];
}
-(void)viewWillAppear:(BOOL)animated{
    [self.searchController.searchBar setHidden:NO];
}

#pragma mark - 公钥存储本地
-(void)memoryPublicKeys:(NSString *)key value:(NSString *)value{
    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
    NSDictionary *keysDic = [KLHelp dictionaryWithJsonString:jsonStr];
    NSMutableDictionary *publickeysdic;
    if(keysDic == nil){
        publickeysdic = [NSMutableDictionary dictionary];
    }else{
        publickeysdic = [NSMutableDictionary dictionaryWithDictionary:keysDic];
    }
    [publickeysdic setObject:value forKey:key];
    [SSKeychain setPassword:[KLHelp dictionaryToJson:publickeysdic] forService:@"com.kisslock.guoyang" account:@"publickeysdic"];
}

#pragma mark - 获取钥匙串列表
-(void)getALlBrunchKeys{
    [self.bunchMaster removeAllObjects];
    self.lock_list_arr = [NSMutableArray array];
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI getCreatAndReceivedGroupListWithCompletionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSLog(@"获取分组列表返回数据:%@",operation.responseJSON);
        NSDictionary *dic = operation.responseJSON;
        NSString *isSuccess = [dic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            self.bunchMaster = [NSMutableArray arrayWithArray:[dic objectForKey:@"infor"]];
//            for (NSDictionary *dic in allGroup) {
//                NSString *type = [dic objectForKey:@"type"];
//                if(type.integerValue == 1)
//                   [self.bunchMaster addObject:dic];
//            }
            self.lock_list_arr = [self.bunchMaster copy];
            if(self.lock_list_arr.count == 0){
                //创建无数据和无网时的图片
                [KLHelp setNoDateImageWithView:self.view type:0];
            }else{
                [KLHelp removeImgViewAndNoticeLabel];
            }
            [self.tableView reloadData];
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:error];
    }];
    
}


#pragma mark 扫描二维码优化
- (void)qqStyle {
    //创建参数对象
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    
    //矩形区域中心上移，默认中心点为屏幕中心点
    style.centerUpOffset = 44;
    
    //扫码框周围4个角的类型,设置为外挂式
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_Outer;
    
    //扫码框周围4个角绘制的线条宽度
    style.photoframeLineW = 6;
    
    //扫码框周围4个角的宽度
    style.photoframeAngleW = 24;
    
    //扫码框周围4个角的高度
    style.photoframeAngleH = 24;
    
    style.alpa_notRecoginitonArea = 0.1;
    
    //扫码框内 动画类型 --线条上下移动
    style.anmiationStyle = LBXScanViewAnimationStyle_LineMove;
    
    style.animationImage = [UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_light_green"];
    
    KLRBScanViewController *scanVC = [[KLRBScanViewController alloc] init];
    scanVC.style = style;
    
    scanVC.isQQSimulator =  YES;
    scanVC.isVideoZoom = YES;
    
    [self.navigationController pushViewController:scanVC animated:YES];
}

// 相机权限
- (BOOL)cameraPemission
{
    BOOL isHavePemission = NO;
    if ([AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)])
    {
        AVAuthorizationStatus permission =
        [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        switch (permission) {
            case AVAuthorizationStatusAuthorized:
                isHavePemission = YES;
                break;
            case AVAuthorizationStatusDenied:
            case AVAuthorizationStatusRestricted:
                break;
            case AVAuthorizationStatusNotDetermined:
                isHavePemission = YES;
                break;
        }
    }
    
    return isHavePemission;
}
@end
